package com.nsn.mib.trap.parser;

import java.util.Iterator;

import org.dom4j.Element;

public class ParserMatch {
	
	/*Match pattern in Tree*/
	public static boolean match(Element root,Element pattern)
	{
		
		if(matchNode(root,pattern))//Match Root
		{
			
			if(matchEdges(root,pattern))//Match All Childern
			{
				for(Iterator i = pattern.elementIterator(); i.hasNext(); )
				{
					Element edge = (Element) i.next();
					
					String depReln = edge.getName();
					
					Element child = root.element("depReln");
					if(!match(child,edge))
					{
						return false;
					}
				}
			}
			return true;
		}
		
		return false;
	}
	
	/*Match Node*/
	private static boolean matchNode(Element root,Element pattern)
	{
		String word = root.attributeValue("word");
		String wordPattern = pattern.attributeValue("word");
		
		String tag = root.attributeValue("word");
		String tagPattern = pattern.attributeValue("word");
		
		if(matchString(word,wordPattern) && matchString(tag,tagPattern))
		{
			return true;
		}
		
		return false;
	}
	
	/*Match Edges*/
	private static boolean matchEdges(Element root,Element pattern)
	{
		for(Iterator i = pattern.elementIterator(); i.hasNext(); )
		{
			Element edge = (Element) i.next();
			
			String depReln = edge.getName();
			
			//if(!root.matches(depReln))
			if(root.selectSingleNode(depReln) == null)
			{
				return false;
			}
		}
		
		return true;
	}
	
	/*Match String*/
	private static boolean matchString(String word,String patterns)
	{
		if(patterns == null || patterns.isEmpty())
		{
			return true;
		}
		if(word.contains(patterns))
		{
			return true;
		}
		
		return false;
	}
}
